﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System.Threading;

public class HRNProxy {
    public HRNProxy() {
        
    }

    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetSetOption(IntPtr Internet, int Option, IntPtr Buffer, int BufferLength);
    public static void DisableProxy() {
        RegistryKey regKey = null;
        try {
            regKey = Is64BitControl();
            regKey.SetValue("ProxyEnable", false, RegistryValueKind.DWord);
            RefreshInternetExplorerSettings();
            regKey.Close();
        } catch (Exception ex) {
            MessageBox.Show(ex.ToString());
        }
    }

    public struct Struct_INTERNET_PROXY_INFO {
        public int dwAccessType;
        public IntPtr proxy;
        public IntPtr proxyBypass;
    };
    public static void SetProxy(string proxy) {
        string ip = proxy.Split(':')[0];
        string port = proxy.Split(':')[1];
        SetProxy(ip.ToString(), Convert.ToInt16(port.ToString()));        ///////////////////
    }
    public static void SetProxy(string ServerName, int port) {
        RegistryKey regkey = null;
        regkey = Is64BitControl();
        //regkey1 = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", RegistryKeyPermissionCheck.ReadWriteSubTree);
        regkey.SetValue("ProxyServer", ServerName + ":" + port.ToString(), RegistryValueKind.Unknown);
        regkey.SetValue("ProxyEnable", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryValueKind.DWord);
        RefreshInternetExplorerSettings();
        regkey.Close();
    }
    private static void RefreshInternetExplorerSettings() {
        InternetSetOption(IntPtr.Zero, SET_OPTIONS.INTERNET_OPTION_SETTINGS_CHANGED.GetHashCode(), IntPtr.Zero, 0);  //INTERNET_OPTION_SETTINGS_CHANGED - 39
        InternetSetOption(IntPtr.Zero, SET_OPTIONS.INTERNET_OPTION_REFRESH.GetHashCode(), IntPtr.Zero, 0);          //INTERNET_OPTION_REFRESH   - 37
    }
    public static void OpenLanSettings() {
        System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
        proc.FileName = @"C:\\Windows\\System32\\RunDll32.exe";
        proc.Arguments = "shell32.dll,Control_RunDLL inetcpl.cpl,Internet,4";
        Process.Start(proc);
        //SendKeys.Send("{TAB}{TAB}{TAB}{TAB}{TAB}{ENTER}");
        SendKeys.Send("{TAB}{TAB}{TAB}{TAB}{ENTER}");
    }
    public void OpenProperties() {
        Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL inetcpl.cpl");
    }

    [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);
    public static bool Is64Bit() {
        bool retVal;
        IsWow64Process(System.Diagnostics.Process.GetCurrentProcess().Handle, out retVal);
        return retVal ;
    }
    static bool Is64BitProcess {
        get {
            if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is64Bit())) {
                return true;
            } else {
                return false;
            }
        }
    }
    public static RegistryKey Is64BitControl() {
        Microsoft.Win32.RegistryKey registry;
        if (Is64Bit()) {
            registry = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
        } else {
            registry = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
        }
        return registry;
    }

    public enum SET_OPTIONS {
        INTERNET_OPTION_REFRESH = 37,
        INTERNET_OPTION_SETTINGS_CHANGED = 39,
        INTERNET_OPTION_PER_CONNECTION_OPTION = 75
    };
    internal static bool CanPing(string address) {
        Ping ping = new Ping();

        try {
            PingReply reply = ping.Send(address, 2000);
            if (reply == null) return false;

            return (reply.Status == IPStatus.Success);
        } catch (PingException e) {
            return false;
        }
    }
    public static bool PingHost(string _HostURI, int _PortNumber) {
        try {

            TcpClient client = new TcpClient(_HostURI, _PortNumber);
            //client.Connect(_HostURI, _PortNumber);
            if(client.Connected)
                client.Close();
            return true;
        } catch{
            //throw new Exception("Error pinging host:'" + _HostURI + ":" + _PortNumber.ToString() + "'", ex);
            return false;
        }
    }
    public static bool PingHostThread(string _HostURI, int _PortNumber) {
        try{
        var th = new Thread(() => {
            PingHost(_HostURI,_PortNumber);
            Application.Run();
        });
        th.Start();
        th.Join();
        return true;
        } catch {
            return false;
        }
    }
    public static bool SoketConnect(string host, int port) {
        var is_success = false;
        try {
            var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
            System.Threading.Thread.Sleep(500);
            var hip = IPAddress.Parse(host);
            var ipep = new IPEndPoint(hip, port);
            connsock.Connect(ipep);
            if (connsock.Connected) {
                is_success = true;
            }
            connsock.Close();
        } catch (Exception) {
            is_success = false;
        }
        return is_success;
    }


}
